package com.spring.security;

import com.spring.security.properties.OAuth2ClientProperties;
import com.spring.security.properties.SecurityProperties;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;


/**
 * 认证服务器
 */
@Configuration
@EnableAuthorizationServer
public class HkAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailService;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //保存到内存中
        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
        //判断系统是否配置
        if (ArrayUtils.isNotEmpty(securityProperties.getOauth2().getClients())) {
            //循环
            for (OAuth2ClientProperties config : securityProperties.getOauth2().getClients()) {
                builder.withClient(config.getClientId())
                        .secret(new BCryptPasswordEncoder().encode(config.getClientSecret()))
                        //token令牌过期时间  秒
                        .accessTokenValiditySeconds(config.getAccessTokenValiditySeconds())
                        //刷新令牌时间
                        .refreshTokenValiditySeconds(config.getRefreshTokenValiditySeconds())
                        //权限
                        .scopes("all", "read", "write")
                        //授权模式
                        .authorizedGrantTypes("password", "authorization_code", "refresh_token");
            }

        }

    }
}

